<template>
  <div id="app">
    <el-container v-if="isAuthenticated">
      <el-header>
        <el-menu
          mode="horizontal"
          :router="true"
          background-color="#545c64"
          text-color="#fff"
          active-text-color="#ffd04b"
        >
          <el-menu-item index="/dashboard">首页</el-menu-item>
          <el-menu-item index="/wallet">钱包管理</el-menu-item>
          <el-menu-item index="/transactions">交易记录</el-menu-item>
          <el-menu-item index="/mint-nft">铸造NFT</el-menu-item>
          <div class="user-info">
            <span>{{ username }}</span>
            <el-button type="text" @click="logout">退出</el-button>
          </div>
        </el-menu>
      </el-header>
      <el-main>
        <router-view />
      </el-main>
    </el-container>
    <router-view v-else />
  </div>
</template>

<script>
export default {
  name: "App",
  computed: {
    isAuthenticated() {
      return !!localStorage.getItem("token");
    },
    username() {
      const user = JSON.parse(localStorage.getItem("user") || "{}");
      return user.username || "";
    },
  },
  methods: {
    logout() {
      localStorage.removeItem("token");
      localStorage.removeItem("user");
      this.$router.push("/login");
    },
  },
  created() {
    // 如果用户已登录，但访问的是登录或注册页面，则重定向到首页
    if (
      this.isAuthenticated &&
      (this.$route.path === "/login" || this.$route.path === "/register")
    ) {
      this.$router.push("/dashboard");
    }
    // 如果用户未登录，且访问的不是登录或注册页面，则重定向到登录页面
    else if (
      !this.isAuthenticated &&
      this.$route.path !== "/login" &&
      this.$route.path !== "/register"
    ) {
      this.$router.push("/login");
    }
  },
};
</script>

<style>
#app {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: #2c3e50;
  height: 100vh;
}

.el-header {
  padding: 0;
}

.el-menu {
  display: flex;
}

.user-info {
  margin-left: auto;
  color: white;
  display: flex;
  align-items: center;
  padding-right: 20px;
}

.user-info span {
  margin-right: 10px;
}
</style>
